# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
""" """
import string
import random
import json
import uuid
import time
import os
import logging
import requests
from typing import Union
from logging.handlers import RotatingFileHandler
from datetime import datetime


def get_time_desc(total_seconds):
    """将秒数转换为X分、X小时等更加清晰易懂的描述"""
    total_seconds = int(total_seconds)
    if total_seconds < 1:
        time_desc = f"不到1秒"
    elif 1 <= total_seconds < 60:
        time_desc = f"{total_seconds}秒"
    elif 60 <= total_seconds < 3600:
        minutes, remainder_seconds = divmod(total_seconds, 60)
        if remainder_seconds == 0:
            time_desc = f"{minutes}分钟"
        else:
            time_desc = f"{minutes}分{remainder_seconds}秒"
    else:
        hours, remainder_seconds1 = divmod(total_seconds, 3600)
        minutes, remainder_seconds2 = divmod(remainder_seconds1, 60)
        if minutes == 0:
            if remainder_seconds2 == 0:
                time_desc = f"{hours}小时"
            else:
                time_desc = f"{hours}小时{remainder_seconds2}秒"
        else:
            if remainder_seconds2 == 0:
                time_desc = f"{hours}小时{minutes}分钟"
            else:
                time_desc = f"{hours}小时{minutes}分{remainder_seconds2}秒"
    return time_desc


def calc_time_interval(start_time_str: str, end_time_str: str) -> str:
    """
    计算两个时间字符串之间的间隔，并返回格式化的时间间隔字符串。

    :param start_time_str: 开始时间字符串，格式为 'YYYY-mm-dd HH:MM:SS'
    :param end_time_str: 结束时间字符串，格式为 'YYYY-mm-dd HH:MM:SS'
    :return: 格式化的时间间隔字符串
    """
    # 检查开始时间字符串是否为空
    if not start_time_str:
        return "0秒"
    # 将时间字符串转换为 datetime 对象
    start_time = datetime.strptime(start_time_str, "%Y-%m-%d %H:%M:%S")
    end_time = datetime.strptime(end_time_str, "%Y-%m-%d %H:%M:%S")
    # 计算时间差
    time_difference = end_time - start_time
    # 获取总秒数
    total_seconds = int(time_difference.total_seconds())
    # 获取时间描述
    time_desc = get_time_desc(total_seconds)
    return time_desc


def setup_logging(
    log_level: str = "INFO",
    write_log: bool = True,
    log_dir: str = "./logs",
    log_file: str = "info.log",
    max_bytes: int = 104857600,
    backup_count: int = 5,
):
    """
    日志格式化打印
    :param log_level: 打印高于等于设定级别的日志。DEBUG < INFO < WARNING < ERROR < CRITICAL
    :param write_log: 是否需要将日志写入到文件
    :param log_dir: 日志文件目录
    :param log_file: 日志文件名
    :param max_bytes: 单个日志文件的最大字节数
    :param backup_count: 保留的日志文件个数
    :return: None
    """
    # 创建日志器
    logger = logging.getLogger()
    logger.setLevel(log_level)  # 设置日志级别
    # 移除所有已经存在的处理器
    logger.handlers.clear()
    # 设置日志格式
    formatter = logging.Formatter("%(asctime)s [%(levelname)s]：%(message)s")
    # 创建一个流处理器，输出到控制台
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    # 根据参数决定是否也将日志写入文件
    if write_log:
        # 确保日志目录存在
        os.makedirs(log_dir, exist_ok=True)
        # 创建一个循环文件处理器，自动根据大小切割
        file_handler = RotatingFileHandler(
            os.path.join(log_dir, log_file),
            maxBytes=max_bytes,
            backupCount=backup_count,
        )
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)


setup_logging()


str_range = list(string.ascii_letters)


def random_str(str_len=32) -> str:
    """生成指定长度的随机字符串"""
    random_str_list = []
    for x in range(str_len):
        current_str = random.choice(str_range)
        random_str_list.append(current_str)
    result = "".join(random_str_list)
    return result


def data2beautify(data: Union[dict, list]):
    """
    字典或列表类型的数据，进行美化输出
    :param data: 字典类型数据
    :return: 格式化数据
    """
    data = json.dumps(data, indent=4, ensure_ascii=False)
    return data


def create_uuid1():
    """生成UUID随机字符串"""
    uuid_1 = str(uuid.uuid1())
    return uuid_1


def extract_element_by_proportion(
    target_list: list, extarct_scale: list, extarct_num: int = 1
) -> list:
    """
    从列表中按比例抽取指定个数的元素
    :param target_list: 需要抽取的列表对象
    :param extarct_scale: 每个元素被抽取的比例。列表对象中每个元素都需要指定一个抽取比例，所有元素的抽取比例之和必须等于1
    :param extarct_num: 抽取的元素个数
    :return: 被抽取元素组成的列表
    """
    element = random.choices(target_list, extarct_scale, k=extarct_num)
    return element


def post_json(url: str, data, log_switch: bool = True, **kwargs) -> dict:
    """
    发送post请求，请求内容为json数据
    :param url: 请求url
    :param data: 请求体
    :param log_switch: 日志开关
    :return: 接口响应
    """
    headers = kwargs.get("headers")
    if headers:
        ...
    else:
        headers = {"Content-Type": "application/json"}
    if log_switch:
        logging.info(f"[请求消息]向{url}接口发起POST请求：\n{data2beautify(data)}")
    res = requests.post(url, data=json.dumps(data), headers=headers, timeout=300).json()
    if log_switch:
        logging.info(f"[响应消息]从{url}接口收到响应：\n{data2beautify(res)}")
    return res


def get_now_time() -> str:
    """
    获取当前时间，格式为YYYY-mm-dd HH:MM:SS
    :return: 当前时间
    """
    not_time = time.strftime("%Y-%m-%d %H:%M:%S")
    return not_time


if __name__ == "__main__":
    print(random_str(32))
